package cn.iocoder.yudao.module.mqtt.task;

import cn.hutool.core.util.ObjUtil;
import cn.iocoder.yudao.module.mqtt.constant.SystemConstants;
import cn.iocoder.yudao.module.mqtt.dal.dataobject.device.DeviceDO;
import cn.iocoder.yudao.module.mqtt.dal.dataobject.devicelatestflow.DeviceLatestFlowDO;
import cn.iocoder.yudao.module.mqtt.framework.config.MqttProperties;
import cn.iocoder.yudao.module.mqtt.framework.mqtt.MqttInstanceManager;
import cn.iocoder.yudao.module.mqtt.service.device.DeviceService;
import cn.iocoder.yudao.module.mqtt.service.devicelatestflow.DeviceLatestFlowService;
import cn.iocoder.yudao.module.mqtt.service.devicelatestflowlog.DeviceLatestFlowLogService;
import cn.iocoder.yudao.module.mqtt.service.devicelatestlog.DeviceLatestLogService;
import cn.iocoder.yudao.module.mqtt.service.mqtt.MqttConnectionMonitorService;
import cn.iocoder.yudao.module.mqtt.service.subscribewater.SubscribeWaterService;
import com.esotericsoftware.minlog.Log;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

@Slf4j
@Component
public class MqttConnectionTask {


    @Resource
    MqttConnectionMonitorService mqttConnectionMonitorService;

    @Resource
    MqttInstanceManager mqttInstanceManager;

    @Resource
    private DeviceService deviceService;
    @Resource
    private DeviceLatestFlowService deviceLatestService;
    @Resource
    private DeviceLatestFlowLogService deviceLatestFlowLogService;
    @Resource
    private DeviceLatestLogService deviceLatestLogService;

    public static  boolean Flag = true;
    /**
     * 定期检查MQTT连接状态
     * 10秒重连
     */
    @Scheduled(fixedRateString = "${mqtt.reconnect.monitor-interval:10000}")
    public void checkConnectionStatus() {
      log.info("----------------检查Mqtt连接状态--------" + SystemConstants.MQTT_INIT_SUCCESS);
      if(SystemConstants.MQTT_INIT_SUCCESS){
         // mqttConnectionMonitorService.myCheckConnectionStatus();
          //mqttInstanceManager.sendMessage(1L, "test", "test");
          //mqttInstanceManager.sendMessage(2L, "test", "test");
      }else{
          log.info("Mqtt未初始化成功");
      }
    }

    /**
     * 每天每2小时执行一次更新操作（0点、2点、4点...22点）
     * cron表达式含义：0 0 0/2 * * ?
     * - 0：秒
     * - 0：分
     * - 0/2：小时（从0点开始，每2小时执行一次）
     * - *：日
     * - *：月
     * - ?：周（不指定，避免与日冲突）
     */

//   @Scheduled(cron = "0 0/1 * * * ?")
    @Scheduled(cron = "0 59 1/2 * * ?")
    public void updateEveryTwoHours() {
        Flag = false;
        try{
            log.info("----------------每2小时执行一次更新操作--------");
            List<DeviceDO> list = deviceService.getList(new DeviceDO().setIsUpload("1"));
            for (int i = 0; i < list.size(); i++) {
                System.out.println("进度 -- " + i + "/" + list.size());
                DeviceLatestFlowDO waterFlowDO =  deviceLatestService.saveWater(list.get(i)); //水量 累计
                DeviceLatestFlowDO sunFlowDO = deviceLatestService.saveWaterSun(list.get(i));//瞬时
                DeviceLatestFlowDO hourFlowDO = deviceLatestService.saveWaterHourSun(list.get(i));//瞬时
//                    if(ObjUtil.isNotEmpty(sunFlowDO) || ObjUtil.isNotEmpty(waterFlowDO) ||ObjUtil.isNotEmpty(hourFlowDO)){
//                        deviceLatestLogService.save(waterFlowDO, sunFlowDO, hourFlowDO);
//                    }else{
//                        Log.info("没有数据");
//                    }
                System.out.println(list.get(i).getDeviceName()+"  -- 已完成");
            }

            list.forEach(deviceDO -> {
                deviceLatestService.saveWaterHourSun(deviceDO);//小时
                DeviceLatestFlowDO deviceLatestDO = deviceLatestService.getDeviceLatestByGatewayId(deviceDO.getGatewayId());
                deviceLatestService.uploadJCJ(deviceLatestDO, null);
            });
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            Flag = true;
            log.info("----------------每2小时执行一次更新操作--------w结束"+ Flag);
        }
    }

    /**
     * 1分钟 同步水量信息
     */
    //@Scheduled(cron = "0 0/1 * * * ?")
    public void update() {
        Flag = false;
        try{
            log.info("----------------每1分钟执行一次更新操作--------");
            List<DeviceDO> list = deviceService.getList(new DeviceDO().setIsUpload("1"));
            for (int i = 0; i < list.size(); i++) {
                System.out.println("进度 -- " + i + "/" + list.size());
                DeviceLatestFlowDO waterFlowDO =  deviceLatestService.saveWater(list.get(i)); //水量 累计
                DeviceLatestFlowDO sunFlowDO = deviceLatestService.saveWaterSun(list.get(i));//瞬时

                deviceLatestFlowLogService.createDeviceLatestFlowLog(waterFlowDO,  sunFlowDO);
                System.out.println(list.get(i).getDeviceName()+"  -- 已完成");
            }


        }catch (Exception e){
            e.printStackTrace();
        }finally {
            Flag = true;
            log.info("----------------每2小时执行一次更新操作--------w结束"+ Flag);
        }
    }

    /**
     * 在 Spring 容器初始化完成后执行
     */
    @PostConstruct
    public void init() {
        log.info("MqttConnectionTask 初始化完成，定时任务将在 Spring Boot 加载完成后触发");
    }
}
